﻿App.In = function() {
    return {

        currentFormValues: {},

        getStore: function() {
            var store = new Ext.data.Store({
                autoLoad:true,
				baseParams : {start:0, limit:20},
				proxy: new Ext.data.HttpProxy({
					url : 'inhouse/items'
				}),
                remoteSort: false,
				reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'object_id',
					fields: [{
						name: 'object_id',
						type: 'string'
					},
					{
						name :'obj_name',
						type:'string'
					},
					{
						name :'obj_num',
						type:'string'
					},
					{
						name :'objid',
						type:'string'
					},
					{
						name: 'from_addr',
						allowBlank: false
					},
					{
						name: 'to_addr',
						allowBlank: false
					},
					{
						name: 'from_name',
						allowBlank: false
					},
					{
						name: 'to_name',
						allowBlank: false
					},
					{
						name:'cost_type'
					},
					{
						name:'from_tell'
					},
					{
						name: "to_tell"
					},
					{
						name: "traff_fee"
					},
					{
						name: "mid_fee"
					},
					{
						name: "inst_fee"
					},
					{
						name: "oth_fee"
					},
					{
						name: "saf_fee"
					},
					{
						name:"sum_fee"
					},
					{
						name:"pre_fee"
					},
					{
						name:"staff_name"
					},
					{
						name:"transitf"
					},
					{
						name:"send_type"
					},
					{
						name: "op_time",
						type: 'date',
						dateFormat: 'time'
					}]
				})
            });
            return store;
        },



        submit: function() {
            if (this.form.getForm().isValid()) {
                this.form.getForm().submit({
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: '',
                    success: function(form, action) {
                       var info = action.result.info;
                        if (action.result.success) {
                            if (action.result.method == "Create") {
                                this.form.getForm().reset();
                            } else {
                                this.dlg.hide();
                            }
                            Ext.Msg.alert('信息', info);
                        }else{
                        	Ext.Msg.alert('信息', info);
                        }
                    },
                    failure: function(form, action) {
                        var info = action.result.info;
	    				Ext.Msg.alert('提示', info);
                    }
                });
            }
        },


        createGrid: function(id) {

            var panel = Ext.getCmp(id);

            panel.body.dom.innerHTML = "";

            var sm = new Ext.grid.CheckboxSelectionModel();
            this.grid = new Ext.grid.GridPanel({
            	anchor:'top 50%',
                loadMask: true,
                stripeRows: true,
                tbar: new Ext.PagingToolbar({ 
                	pageSize: 20 ,//分页必须加的参数.最好和store里面的limit保持一致
                	displayInfo: true,
                    store: this.store,
                    items:[
                    {
	                    text: '增加',
	                    scope: this,
	                    handler: this.add
	                },
	               {
	                    text: '编辑',
	                    scope: this,
	                    handler: this.edit
	                },
	                {
	                    text: '删除',
	                    scope: this,
	                    handler: this.del
                },'-', new Ext.ux.form.SearchField({
                    store: this.store,
                    width: 110
                })]}),
                title:"入库管理",//打印必须设置tile
                plugins: [Ext.ux.plugins.Print],//打印按钮
                loadMask: true,
                viewConfig : {autoFill:false,forceFit:true},
                autoHeight:true,
                store: this.store,
                sm: sm,
                columns: [new Ext.grid.RowNumberer(),{
                	hidden:true,
                	dataIndex:'cost_type'
                },{
                    header: "货号",
                    sortable: true,
                    dataIndex: 'objid',
                    renderer: this.highLight
                },
                {
                    header: "货物名称",
                    sortable: true,
                    dataIndex: 'obj_name',
                    renderer: this.highLight
                },
                {
                    header: "件数",
                    sortable: true,
                    dataIndex: 'obj_num',
                    renderer: this.highLight
                },
                {
                    header: "收货人", 
                    sortable: true,
                    dataIndex: 'to_name',
                    renderer: this.highLight
                },
                {
                    header: "收货人电话",
                    sortable: true,
                    dataIndex: 'to_tell'
                },
                {
                    header: "收货地",
                    sortable: true,
                    dataIndex: 'to_addr',
                    renderer: this.highLight
                },
            /*    {
                    header: "发货人",
                    width: 100,
                    sortable: true,
                    dataIndex: 'from_name',
                    renderer: this.highLight
                },
                {
                    header: "发货人电话",
                    width: 100,
                    sortable: true,
                    dataIndex: 'from_tell'
                },
                {
                    header: "发货地",
                    width: 100,
                    sortable: true,
                    dataIndex: 'from_addr',
                    renderer: this.highLight
                },
                {
                    header: "运费",
                    width: 100,
                    sortable: true,
                    dataIndex: 'traff_fee'
                },
                {
                    header: "中转费",
                    width: 100,
                    sortable: true,
                    dataIndex: 'mid_fee'
                },
                {
                    header: "代收费",
                    width: 100,
                    sortable: true,
                    dataIndex: 'inst_fee'
                },
                {
                    header: "保险费",
                    width: 100,
                    sortable: true,
                    dataIndex: 'saf_fee'
                },
                {
                    header: "其它费用",
                    width: 100,
                    sortable: true,
                    dataIndex: 'oth_fee'
                },
               */ {
                	header: "总费用",
                    sortable: true,
                    dataIndex: 'sum_fee'
                },
           /*     {
                	header:"垫付费",
                	sortable:true,
                	dataIndex:'pre_fee'
                },
             */   {
                    header: "入库时间",
                    sortable: true,
                    dataIndex: 'op_time',
                    renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s')
                },
                {
                	header:"货物类型",
                	sortable:true,
                	dataIndex:'transitf'
                },
                {
                    header: "签收人",
                    sortable: true,
                    dataIndex: 'staff_name'
                },
                {
                	header:"送货方式",
                	dataIndex:'send_type',
                	hidden:true
                }
                ]
            });
            panel.add(this.grid);

        },
        getForm: function() {
        	var transitStore = new Ext.data.Store({
            	autoLoad:false,
//				baseParams:{start:0, limit:23},
				proxy: new Ext.data.HttpProxy({
					url : 'transit/items'
				}),
                remoteSort: false,
                reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'transit_id',
					fields: [{
						name: 'transit_id',
						type: 'string'
					},
					{
						name: 'name',
						type: 'string'
					}]
				})
            });
        	 var getCostTypeStore = new Ext.data.Store({
                 autoLoad:false,
 				baseParams : {parent_id:1},//1表示direct表id为1的记录(次store取出parent为1的所有记录)
 				proxy: new Ext.data.HttpProxy({
 					url : 'menu/costype'
 				}),
                 remoteSort: false,
 				reader: new Ext.data.JsonReader({
 					totalProperty : 'totalCount',
 					root : 'rows',
 					idProperty : 'id',
 					fields: [{
 						name: 'name',
 						type:'string'
 					},{
 						name: 'id',
 						type: 'string'
 					}]
 				})
             });
            var form = new Ext.form.FormPanel({
				url:'inhouse/save',
                labelAlign: 'right',
                frame: true,
                waitMsgTarget:true,
              //  defaults:{allowBlank :false},
                items: [{
                    layout:'column',
                    items:[{
                	    defaults:{width  :200},
                        columnWidth:.5,
                        layout: 'form',
                        defaultType : 'textfield',
                        				items : [ {
                        					xtype : 'hidden',
                        					name : 'object_id',
                        					value : ''
                        				}, {
                        					name : 'objid',
                        					allowBlank:false,
                        					fieldLabel : '货号'
                        				}, {
                        					name : 'obj_name',
                        					allowBlank:false,
                        					fieldLabel : '货物名称'
                        				},{
                        					name : 'obj_num',
                        					fieldLabel : '件数',
                        					allowBlank:false,
                        					xtype : 'numberfield',
                        					value : 1,
                        					decimalPrecision:0,
                        					minValue : 0
                        				},{
                        					name : 'from_name',
                        					fieldLabel : '发货人'
                        				}, {
                        					name : 'from_addr',
                        					fieldLabel : '发货地址'
                        				}, {
                        					name : 'from_tell',
                        					xtype : 'numberfield',
                        					fieldLabel : '发货人电话'
                        				},{
                        					name : 'to_name',
                        					allowBlank:false,
                        					fieldLabel : '收货人'
                        				},{
                        					name : 'to_tell',
                        					xtype : 'numberfield',
                        					allowBlank:false,
                        					fieldLabel : '收货人电话'
                        				}, {
                        					name : 'to_addr',
                        					allowBlank:false,
                        					fieldLabel : '收货地址'
                        				},{
                            				xtype : 'radiogroup',
                            				fieldLabel : '是否保价',
                            				items : [
                            						{
                            							boxLabel : '是',
                            							name : 'ppice',
                            							inputValue : 1
                            						},
                            						{
                            							boxLabel : '否',
                            							name : 'ppice',
                            							inputValue : 0,
                            							checked : true,
                            							listeners : {
                            								check : function(checkbox, checked) {
                            									if (checked) {
                            										this.findParentByType('form').getForm()
                            												.findField('price')
                            												.setDisabled(true);// 选中报价金额输入框不可用
                            									} else {
                            										this.findParentByType('form').getForm()
                            												.findField('price')
                            												.setDisabled(false);
                            									}
                            								}
                            							}
                            						} ]
                            			},{
                            				xtype : 'radiogroup',
                            				name : 'transitf',
                            				fieldLabel : '是否中转',
                            				items : [
                            						{
                            							boxLabel : '是',
                            							name : 'transitf',
                            							inputValue : 1
                            						
                            						},
                            						{
                            							boxLabel : '否',
                            							name : 'transitf',
                            							inputValue : 0,
                            							checked : true,
                            							listeners : {
                            								check : function(checkbox, checked) {
                            									if (checked) {
                            										this.findParentByType('form').getForm()
                            												.findField('transit_id')
                            												.setDisabled(true);// 选中报价金额输入框不可用
                            									} else {
                            										this.findParentByType('form').getForm()
                            												.findField('transit_id')
                            												.setDisabled(false);
                            									}
                            								}
                            							}
                            						} ]
                            			}]
                    },{
                        columnWidth:.5,
                        layout: 'form',
                        defaults:{width  :200},
                        defaultType : 'textfield',
                        				items : [{
                        					xtype : 'combo',
                        					fieldLabel : "付款方式",
                        					hiddenName : 'cost_type',
                        					store : getCostTypeStore,
                        					displayField : 'name',
                        					valueField : 'id',
                        					allowBlank:false,
                        					mode : 'remote',
                        					triggerAction : 'all',
                        					editable : false,
                        					emptyText : '选择付款方式....'
                        				},{
                        					name : 'traff_fee',
                        					fieldLabel : '运费',
                        					xtype : 'numberfield',
                        					value : 0,
                        					minValue : 0,
                        				///	enableKeyEvents:true, //监听测试 
                        					listeners : {
                        						change: function() {
                        		                        var traff_fee = parseFloat(this.findParentByType('form').getForm().findField('traff_fee').getValue());
                        		                        var inst_fee = parseFloat(this.findParentByType('form').getForm().findField('inst_fee').getValue());
                        		                        var pre_fee = parseFloat(this.findParentByType('form').getForm().findField('pre_fee').getValue());
                        		                        var mid_fee = parseFloat(this.findParentByType('form').getForm().findField('mid_fee').getValue());
                        		                        var oth_fee = parseFloat(this.findParentByType('form').getForm().findField('oth_fee').getValue());
                        		                        this.findParentByType('form').getForm().findField('sum_fee').setValue(Number(traff_fee+inst_fee+pre_fee+mid_fee+oth_fee));
                        		                    }
                        		                }
                        				}, {
                        					name : 'inst_fee',
                        					fieldLabel : '代收货款',
                        					xtype : 'numberfield',
                        					value : 0,
                        					minValue : 0,
                        					listeners : {
                        						change: function() {
                        		                        var traff_fee = parseFloat(this.findParentByType('form').getForm().findField('traff_fee').getValue());
                        		                        var inst_fee = parseFloat(this.findParentByType('form').getForm().findField('inst_fee').getValue());
                        		                        var pre_fee = parseFloat(this.findParentByType('form').getForm().findField('pre_fee').getValue());
                        		                        var mid_fee = parseFloat(this.findParentByType('form').getForm().findField('mid_fee').getValue());
                        		                        var oth_fee = parseFloat(this.findParentByType('form').getForm().findField('oth_fee').getValue());
                        		                        this.findParentByType('form').getForm().findField('sum_fee').setValue(Number(traff_fee+inst_fee+pre_fee+mid_fee+oth_fee));
                        		                    }
                        		                }
                        				}, {
                        					name : 'pre_fee',
                        					fieldLabel : '垫付费用',
                        					xtype : 'numberfield',
                        					value : 0,
                        					minValue : 0,
                        					listeners : {
                        						change: function() {
                        		                        var traff_fee = parseFloat(this.findParentByType('form').getForm().findField('traff_fee').getValue());
                        		                        var inst_fee = parseFloat(this.findParentByType('form').getForm().findField('inst_fee').getValue());
                        		                        var pre_fee = parseFloat(this.findParentByType('form').getForm().findField('pre_fee').getValue());
                        		                        var mid_fee = parseFloat(this.findParentByType('form').getForm().findField('mid_fee').getValue());
                        		                        var oth_fee = parseFloat(this.findParentByType('form').getForm().findField('oth_fee').getValue());
                        		                        this.findParentByType('form').getForm().findField('sum_fee').setValue(Number(traff_fee+inst_fee+pre_fee+mid_fee+oth_fee));
                        		                    }
                        		                }
                        				},{
                        					name : 'mid_fee',
                        					fieldLabel : '中转费',
                        					xtype : 'numberfield',
                        					value : 0,
                        					minValue : 0,
                        					listeners : {
                        						change: function() {
                        		                        var traff_fee = parseFloat(this.findParentByType('form').getForm().findField('traff_fee').getValue());
                        		                        var inst_fee = parseFloat(this.findParentByType('form').getForm().findField('inst_fee').getValue());
                        		                        var pre_fee = parseFloat(this.findParentByType('form').getForm().findField('pre_fee').getValue());
                        		                        var mid_fee = parseFloat(this.findParentByType('form').getForm().findField('mid_fee').getValue());
                        		                        var oth_fee = parseFloat(this.findParentByType('form').getForm().findField('oth_fee').getValue());
                        		                        this.findParentByType('form').getForm().findField('sum_fee').setValue(Number(traff_fee+inst_fee+pre_fee+mid_fee+oth_fee));
                        		                    }
                        		                }
                        				}, {
                        					name : 'oth_fee',
                        					fieldLabel : '其它费用',
                        					xtype : 'numberfield',
                        					value : 0,
                        					minValue : 0,
                        					listeners : {
                        						change: function() {
                        		                        var traff_fee = parseFloat(this.findParentByType('form').getForm().findField('traff_fee').getValue());
                        		                        var inst_fee = parseFloat(this.findParentByType('form').getForm().findField('inst_fee').getValue());
                        		                        var pre_fee = parseFloat(this.findParentByType('form').getForm().findField('pre_fee').getValue());
                        		                        var mid_fee = parseFloat(this.findParentByType('form').getForm().findField('mid_fee').getValue());
                        		                        var oth_fee = parseFloat(this.findParentByType('form').getForm().findField('oth_fee').getValue());
                        		                        this.findParentByType('form').getForm().findField('sum_fee').setValue(Number(traff_fee+inst_fee+pre_fee+mid_fee+oth_fee));
                        		                    }
                        		                }
                        				}, {
                        					name : 'sum_fee',
                        					fieldLabel : '总费用',
                        					xtype : 'numberfield',
                        					value : 0,
                        					minValue : 0
                        				},{
                            				xtype : 'radiogroup',
                            				name : 'send_type',
                            				fieldLabel : '发货方式',
                            				items : [
                            						{
                            							boxLabel : '自提',
                            							name : 'send_type',
                            							inputValue : 1,
                            							checked : true
                            						
                            						},
                            						{
                            							boxLabel : '送货上门',
                            							name : 'send_type',
                            							inputValue : 0
                            						} ]
                            			},{
                            				name : 'price',
                            				fieldLabel : '保价金额',
                            				xtype : 'numberfield',
                            				allowBlank:false,
                            				disabled:true,
                            				value : 0,
                            				minValue : 0
                            			},{

                            				fieldLabel : '中转公司',
                            				xtype : 'combo',
                            				hiddenName : "transit_id",
                            				store : transitStore,
                            				disabled:true,
                            				displayField : 'name',
                            				valueField : 'transit_id',
                            				typeAhead : true,
                            				mode : 'remote',
                            				forceSelection : true,
                            				allowBlank:false,
                            				triggerAction : 'all',
                            				emptyText : '选择中转公司....',
                            				selectOnFocus : true,
                            				editable : false,
                                            listeners : {
                                        		expand:function(comb){
                                        			comb.getStore().reload();
                                        		}
                                        	}

                            			} ]
                    }]
                },{
                	fieldLabel: '发往物流部',
            		xtype:'combo',
            		width :720,
            		hiddenName :"to_cmp",
            		store: new Ext.data.Store({
                    	autoLoad:false,
            			proxy: new Ext.data.HttpProxy({
            				url : 'localtion/localtionList'
            			}),
                        remoteSort: false,
                        reader: new Ext.data.JsonReader({
            				totalProperty : 'totalCount',
            				root : 'rows',
            				idProperty : 'local_id',
            				fields: [{
            					name: 'local_id',
            					type: 'string'
            				},
            				{
            					name: 'local_name',
            					type: 'string'
            				}]
            			})
                    }),
                    displayField:'local_name',
                    valueField :'local_id',
                    mode: 'remote',
                    triggerAction: 'all',
                    editable: false,
                    emptyText:'选择货物要发往的物流部....(入库物流部是登陆选择的地点)'
                },{
    					name : 'brief',
    					width :720,
    					height:110,
    					fieldLabel : '备注',
    					xtype:'textarea'
    				}],
                buttons: [{
                    text: '确定',
                    scope: this,
                    handler: function() {
                        this.submit();
                    }
                },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        var f = this.form.getForm();
                        f.reset();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }]
            });
            
            return form;
        },
        getDialog: function() {
            var dlg = new Ext.Window({
                width: 550,
                height: 430,
                maximized:true,
                title: '',
                plain: true,
                closable: true,
                resizable: false,
                frame: true,
                layout: 'fit',
                closeAction: 'hide',
                border: false,
                modal: true,
                items: [this.form],
                listeners: {
                    scope: this,
                    render: function(fp) {
                        this.form.getForm().waitMsgTarget = fp.getEl();
                    },
                    show: function() {
                        var f = this.form.getForm();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    },
                    beforehide: function(){
                    	this.store.reload();
                    }
                }
            });
            return dlg;
        },
        highLight: function(value) {
        	var key = App.In.grid.store.baseParams.query;
        	var v = value ? value.toString() : '';
        	if (Ext.isString(v) & Ext.isString(key)) {
        		if (key.length > 0) {
        			var re = new RegExp(key, "g");
        			return v.replace(re, "<span style='color:red;background-color:yellow;'>" + key + "</span>");
        		} else {
        			return v;
        		}
        	} else {
        		return v;
        	}
        },
        add: function() {
            Ext.apply(this.currentFormValues, {
            	object_id: '',
                objid: "",
                obj_name: "",
                obj_num: 1,
                from_name: "",
                from_addr: "",
                from_tell: "",
                to_name: "",
                to_addr: "",
                to_tell: "",
                traff_fee:0,
                inst_fee:0,
                mid_fee:0,
                oth_fee:0,
                ppice:0,
                price:0,
                cost_type:'',
                transit_id:'',
                transitf:0,
                brief:""
            });
            this.dlg.setTitle("增加货号");
            this.dlg.show();
        },

        edit: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                this.dlg.setTitle("编辑货号");
                var rec = this.grid.getSelectionModel().getSelected();
                Ext.apply(this.currentFormValues, {
                	 object_id: rec.json.object_id,
                     objid: rec.json.objid,
                     obj_name: rec.json.obj_name,
                     obj_num: rec.json.obj_num,
                     from_name: rec.json.from_name,
                     from_addr: rec.json.from_addr,
                     from_tell: rec.json.from_tell,
                     to_name: rec.json.to_name,
                     to_addr: rec.json.to_addr,
                     to_tell: rec.json.to_tell,
                     traff_fee:rec.json.traff_fee,
                     inst_fee:rec.json.inst_fee,
                     mid_fee:rec.json.mid_fee,
                     oth_fee:rec.json.oth_fee,
//                     cost_type:rec.json.cost_type,
                     ppice:rec.json.ppice,
                     price:rec.json.price,
                     transitf:rec.json.transitf,
                     brief:rec.json.brief,
                     staff_name:rec.json.staff_name
                });
                this.dlg.show();
            } else {
                Ext.Msg.alert('信息', '请选择要编辑的货号。');
            }
        },

        del: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                var recs = this.grid.getSelectionModel().getSelections();
                var ids = [];
                var titles = '';
                for (var i = 0; i < recs.length; i++) {
                    var data = recs[i].data;
                    ids.push(data.object_id);
                    titles += data.objid + '<br>';
                }
                Ext.Msg.confirm('删除用户', '确定删除货号？<br><font color="red">' + titles + '</font>',
                function(btn) {
                    if (btn == 'yes') {
						Ext.Ajax.request({
							method:'post',
							url:'inhouse/remove',
							params:{
								ids:ids.toString()
							},
							success: function(resp, opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								if(result.success=='true') {
									Ext.Msg.alert('信息', info);
                                    App.In.store.reload();
								}else {
                                    Ext.Msg.alert('信息', info);
                                }
							},
							failure: function(resp,opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								Ext.Msg.alert('提示', info); 
							}
						});
                    }
                });
            } else {
                Ext.Msg.alert('信息', '请选择要删除的用户！');
            }
        },


        render: function(id) {
            if (!this.store) {
                this.store = this.getStore();
            };
            if (!this.form) {
                this.form = this.getForm();
            };
            if (!this.dlg) {
                this.dlg = this.getDialog();
            };
            this.createGrid(id);

        }
    };
} ();
